package com.asia5b.a5mall.middleware.core

import android.app.Activity
import com.asia5b.a5bmall.resource.ResString
import java.lang.ref.WeakReference
import java.util.*

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   Activity栈
 */
class ActivityTask {

    /**
     * @Name  activityList
     * @Type  java.util.ArrayList
     * @Note  Activity序列
     */
    private var activityList = ArrayList<WeakReference<Activity>>()

    /**
     * 伴生对象
     */
    companion object {
        /**
         * @Name  com.asia5b.a5mall.middleware.core.JavaShopActivityTask.Companion.instance
         * @Type  com.asia5b.a5mall.middleware.core.JavaShopActivityTask
         * @Note  单例
         */
        val instance = ActivityTask()
    }

    /**
     * 构造方法私有化
     */
    private constructor()

    /**
     * @Note   获取当前应用Activity栈
     * @return 当前应用Activity栈
     */
    fun getActivityArray(): ArrayList<WeakReference<Activity>> {
        return activityList
    }

    /**
     * @Note   获取当前栈顶Activity
     * @return 当前栈顶Activity
     */
    fun peekTopActivity(): Activity? {
        if (activityList != null && activityList.size > 0) {
            val ref = activityList.get(activityList.size - 1)
            if (ref != null && ref!!.get() != null) {
                return ref!!.get()
            }
        }
        return null
    }

    /**
     * @Note   Activity创建时调用 添加activity到栈中
     * @param  activity 新创建的Activity
     */
    fun pushToActivityStack(activity: Activity) {
        activityList.add(WeakReference(activity))
        ResString.resActivity = activityList.get(activityList.size - 1).get()
    }

    /**
     * @Note   activity销毁时调用 在栈中移除销毁的Activity
     * @param  activity 销毁的Activity
     */
    fun popFromActivityStack(activity: Activity) {
        for (x in activityList.indices) {
            val ref = activityList.get(x)
            if (ref != null && ref!!.get() != null && ref!!.get() === activity) {
                activityList.remove(ref)
                return
            }
        }
    }

    /**
     * @Note   清除当前Activity栈
     */
    fun clearActivityStack() {
        try {
            for (ref in activityList) {
                if (ref != null && ref!!.get() != null && !ref!!.get()!!.isFinishing()) {
                    ref!!.get()!!.finish()
                }
            }
        } catch (e: Throwable) {

        } finally {
            activityList.clear()
        }
    }

    /**
     * @Note   判断当前Activity栈是否为空
     * @return Boolean 是否为空
     */
    fun isActivityStackEmpty(): Boolean {
        return sizeOfActivityStack() == 0
    }

    /**
     * @Note   获取当前Activity栈大小
     * @return 当前Activity栈大小
     */
    fun sizeOfActivityStack(): Int {
        return activityList.size
    }
}